from flask import Flask, jsonify, render_template
import numpy as np
import threading
import time

app = Flask(__name__)

class DataGenerator:
    def __init__(self, sample_rate=1000, channels=2):
        self.sample_rate = sample_rate
        self.channels = channels
        # 10分钟数据缓冲区：600秒 * 1000点/秒 = 600,000点
        self.buffer_size = 600 * sample_rate
        self.data_buffer = np.zeros((self.buffer_size, channels), dtype=np.uint16)
        self.lock = threading.Lock()
        self.running = True
        self.write_index = 0
        self.data_ready = threading.Event()
        
    def generate_data(self):
        """模拟数据采集线程，每秒更新一次数据"""
        while self.running:
            # 生成1秒的数据：1000点 * 2通道
            new_data = np.random.randint(0, 65535, (self.sample_rate, self.channels), dtype=np.uint16)
            
            with self.lock:
                # 将新数据写入缓冲区
                start_idx = self.write_index
                end_idx = start_idx + self.sample_rate
                
                if end_idx <= self.buffer_size:
                    self.data_buffer[start_idx:end_idx] = new_data
                else:
                    # 处理缓冲区回绕
                    remaining = self.buffer_size - start_idx
                    self.data_buffer[start_idx:] = new_data[:remaining]
                    self.data_buffer[:end_idx - self.buffer_size] = new_data[remaining:]
                
                # 更新写入位置
                self.write_index = end_idx % self.buffer_size
                self.data_ready.set()
            
            time.sleep(1)  # 模拟1秒采集周期
    
    def get_latest_data(self, num_points=1000):
        """获取最新数据切片"""
        with self.lock:
            start_idx = (self.write_index - num_points) % self.buffer_size
            if start_idx + num_points <= self.buffer_size:
                return self.data_buffer[start_idx:start_idx+num_points].copy()
            else:
                # 处理数据跨越缓冲区边界的情况
                part1 = self.data_buffer[start_idx:]
                part2 = self.data_buffer[:num_points - len(part1)]
                return np.vstack((part1, part2))
    
    def get_full_buffer(self):
        """获取整个缓冲区数据（用于初始化）"""
        with self.lock:
            return self.data_buffer.copy()

# 初始化数据生成器
data_gen = DataGenerator()
thread = threading.Thread(target=data_gen.generate_data)
thread.daemon = True
thread.start()

@app.route('/')
def index():
    """主页面服务"""
    return render_template('index.html')

@app.route('/init_data')
def get_init_data():
    """提供初始化数据API"""
    data = data_gen.get_full_buffer()
    # 转换为前端需要的格式
    channels = {}
    for i in range(data_gen.channels):
        channels[f'ch{i}'] = data[:, i].tolist()
    return jsonify(channels)

@app.route('/update_data')
def get_update_data():
    """提供增量更新数据API"""
    data = data_gen.get_latest_data(1000)  # 获取最新的1000个点
    # 转换为前端需要的格式
    channels = {}
    for i in range(data_gen.channels):
        channels[f'ch{i}'] = data[:, i].tolist()
    return jsonify(channels)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, threaded=True)